
const Koa = require('koa');
const router = require('koa-router')();
const serve = require('koa-static');
const path =require('path');
const fs = require('fs');
const data = require('./data.json');

const app = new Koa();

const main = serve(__dirname+ "/webRoot");
app.use(main);


app.use(async (ctx,next) => {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}`);
    await next();
});

router.get('/api',async (ctx,next) => {
    ctx.response.status=200;
    ctx.response.type="html";
    ctx.response.body = fs.createReadStream('./webRoot/static/2.html','utf-8');
    
});

router.get('/api/:id',async (ctx,next) => {
    var id=ctx.params.id;
    var json='';//返回的json对象
    //获取对应id的数据
    var item= data.filter(function(item){  
        return item.id===id;
    });

   if(item.length !== 0){
       //访问次数加一
       item[0].count+=1;
      // json=`'{ "error" : 0,"data" :${JSON.stringify(item[0])}}'`;
      json=`{ "error" : 0,"data" :${JSON.stringify(item[0])}}`;
       ctx.response.status=200;
    //   ctx.response.body =`{title : ${item[0].title}}`;
   }else{
       json={ "error" : 1,"data" : "null"};
       ctx.response.status=404;
   }
   //ctx.response.type=""
      ctx.response.body =json;
});


app.use(router.routes());
// 在端口3000监听:
app.listen(3000);
//console.log(data)

